/**************************************************************************************
 *
 * @(#) SecurityConfig.java
 * @Package com.jgdt.jgdtkasannong_university_gene_backend.config
 **************************************************************************************/
package com.jgdt.jgdtkasannong_university_gene_backend.config.security;

import com.jgdt.jgdtkasannong_university_gene_backend.common.example.global.CustomAuthenticationEntryPoint;
import com.jgdt.jgdtkasannong_university_gene_backend.config.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import java.util.Arrays;

/**
 * @description: Security 配置文件
 * @author: huangAn
 * @createDate: 2025/04/18
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling(handling -> handling
                        .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                )
                //自定义认证入口
//                .addFilterBefore(new CustomExceptionTranslationFilter(new CustomAuthenticationEntryPoint()), ExceptionTranslationFilter.class)
                //自定义认证入口
                .authorizeHttpRequests(auth -> auth
                        // 1. 首先放行 OPTIONS 预检请求（所有路径）
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()

                        // 2. 放行具体的登录相关接口
                        .requestMatchers("/api/user/auth/**"
                                ,"/swagger-resources/**"
                                ,"/webjars/**"
                                ,"/images/**"
                                ,"/data/**"
                                ,"/test/kasTest/**"    //todo 测试接口本地先放开
                                ,"/swagger-ui.html"
                                , "/v3/api-docs"
                        ).permitAll()

                        // 3. 其他需要认证的接口
                        .anyRequest().authenticated()
                );
                //无需认证的配置 方式二:
//                .requestMatchers(
//                        HttpMethod.OPTIONS,"/**", //todo 本地运行 处理 OPTIONS请求 跨域问题,非本地环境可注释
//                        "/api/user/auth/**"
//                        , "/swagger-ui.html"
//                        , "/swagger-resources/**"
//                        , "/v3/api-docs"
//                        , "/webjars/**"
//                        ,"/images/**"
//                        ,"/data/**"
//                        ,"/test/**"    //todo 测试接口本地先放开
//                ).permitAll() //先放行
//                .anyRequest().authenticated();//后全局认证

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }


    /**
     * 此方法会完全绕过Spring Security的过滤器链，适用于无需鉴权的内部接口
     * @return
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                .requestMatchers(
                        "/swagger-ui/**",
                        "/v3/api-docs/**",
                        "/swagger-resources/**"
                );
    }

    /**
     * todo 本地运行 处理 OPTIONS请求 跨域问题,非本地环境可注释
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors().and()          // 启用CORS
                .csrf().disable()
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()  // 放行所有OPTIONS请求
                        .anyRequest().authenticated()  // 其他请求需要认证
                );
        return http.build();
    }

    /**
     * todo 本地运行 处理 OPTIONS请求 跨域问题,非本地环境可注释
     * @return
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:5173"));
        config.setAllowedMethods(Arrays.asList("*"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);
        config.setMaxAge(1800L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 覆盖所有路径
        return source;
    }



}


